package com.library.ui;

import com.library.dao.BorrowDAO;
import com.library.dao.BookDAO;
import com.library.model.Book;
import com.library.model.BorrowInfo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class ReturnBookPanel extends JPanel {
    private JTextField readerNumberField;
    private JTextField bookNumberField;
    private BorrowDAO borrowDAO = new BorrowDAO();
    private BookDAO bookDAO = new BookDAO();

    public ReturnBookPanel() {
        setLayout(new GridLayout(3, 2));

        JLabel readerNumberLabel = new JLabel("读者编号：");
        readerNumberField = new JTextField();
        JLabel bookNumberLabel = new JLabel("书号：");
        bookNumberField = new JTextField();
        JButton returnBtn = new JButton("还书");

        returnBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String readerNumber = readerNumberField.getText();
                String bookNumber = bookNumberField.getText();

                try {
                    // 检查是否有该借阅记录
                    List<BorrowInfo> borrowInfos = borrowDAO.getBorrowInfoByReader(readerNumber);
                    boolean found = false;
                    for (BorrowInfo borrowInfo : borrowInfos) {
                        if (borrowInfo.getBookNumber().equals(bookNumber)) {
                            found = true;
                            break;
                        }
                    }

                    if (!found) {
                        JOptionPane.showMessageDialog(null, "未找到该借阅记录");
                        return;
                    }

                    // 还书操作，更新图书库存
                    Book book = bookDAO.getBookByNumber(bookNumber);
                    book.setInventory(book.getInventory() + 1);
                    if (!bookDAO.update(book)) {
                        throw new SQLException("更新图书库存失败");
                    }

                    // 删除借阅记录
                    if (!borrowDAO.deleteBorrowRecord(readerNumber, bookNumber)) {
                        throw new SQLException("删除借阅记录失败");
                    }

                    JOptionPane.showMessageDialog(null, "还书成功");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "还书失败，请稍后重试");
                }
            }
        });

        add(readerNumberLabel);
        add(readerNumberField);
        add(bookNumberLabel);
        add(bookNumberField);
        add(new JLabel());
        add(returnBtn);
    }
}